package com.shr.xsunmvc.servlet.packer;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.shr.xsunmvc.Xsun;
import com.shr.xsunmvc.render.Render;

/**
 * 增强的response
 * @author sun haoran
 *
 */
public class Response {

	private HttpServletResponse response ;
	private Render render ;
	
	
	public Response(HttpServletResponse servletResponse) {
		this.response = servletResponse ;
		this.render = Xsun.me().getRender() ;
	}
	
	
	/**
	 * 写入文本
	 * @param text
	 */
	public void text(String text){
		response.setContentType("text/plan;charset=UTF-8");
		this.print(text) ;
	}


	private void print(String text) {
		try {
			OutputStream output = response.getOutputStream() ;
			output.write(text.getBytes());
			output.flush();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 写入html
	 * @param html
	 */
	public void html(String html){
		response.setContentType("text/html;charset=UTF-8");
		this.print(html);
	}
	
	public void addCookie(String key, String value){
		Cookie cookie = new Cookie(key, value) ;
		response.addCookie(cookie);
	}
	
	/**
	 * 渲染到指定页面
	 * @param index
	 */
	public void render(String index){
		render.render(index, null);
	}
	
	/**
	 * 转发请求
	 * @param index
	 */
	public void redirect(String index){
		try {
			response.sendRedirect(index);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public HttpServletResponse getResponse(){
		return response ;
	}

}
